<template>
  <div class="accounting-form">
    <el-form ref="formRef" label-position="top" :model="formData" :rules="formRules">
      <el-form-item label="填报方式：" prop="replyType">
        <div class="fill-type-radio">
          <el-radio-group v-model="formData.replyType">
            <el-radio label="MODEL">{{ $t18('model.MODEL') }}</el-radio>
            <el-radio label="LCA">{{ $t18('model.LCA') }}</el-radio>
          </el-radio-group>
        </div>
        <div class="fill-type-tips"
          >请填写以上产品碳足迹核算信息。您有两种填报方式：1、选择对应我的模型填报；2、通过该产品的碳足迹报告填报</div
        >
      </el-form-item>
      <el-row class="form-container" :gutter="20">
        <el-col :span="6" v-if="formData.replyType === 'MODEL'">
          <el-form-item label="选择已有模型：" prop="modelNo">
            <div class="select-model-input">
              <el-select v-model="formData.modelNo" placeholder="请选择">
                <el-option
                  v-for="item in modelList"
                  :key="item.modelNo"
                  :label="item.name"
                  :value="item.modelNo"
                ></el-option>
              </el-select>
            </div>
            <div class="select-model-tips"
              >还没有模型，<a class="tips-href" @click="routerToCreateModel">先去建模></a></div
            >
          </el-form-item>
        </el-col>
        <template v-else-if="formData.replyType === 'LCA'">
          <el-col :span="6">
            <el-form-item label="碳排放值：" prop="emissionResult">
              <el-input
                type="number"
                @wheel.stop.prevent
                v-decimal-only:6
                v-model="formData.emissionResult"
                placeholder="请输入"
              >
                <template #suffix>kg&nbsp;CO₂e</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号：" prop="specification">
              <el-input v-model="formData.specification" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核算数量：" prop="num" class="g-unit-item">
              <el-input
                v-model="formData.num"
                placeholder="请输入核算数量"
                clearable
                maxlength="19"
                v-positive-only:6
                type="number"
                @wheel.stop.prevent
              >
                <template #append>
                  <el-select v-model="formData.unit" style="width: 70px">
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in modelUnitAllOption"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="单位重量："
              prop="weight"
              class="g-unit-item"
              v-if="!isWeightUnitComputed"
            >
              <el-input
                v-model="formData.weight"
                placeholder="核算数量为1的重量"
                clearable
                maxlength="19"
                v-positive-only:6
                type="number"
                @wheel.stop.prevent
              >
                <template #append>
                  <el-select v-model="formData.weightUnit" style="width: 70px">
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="(item, index) in WeightUnitOption"
                      :key="index"
                    ></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数据采集周期：" prop="baseYear">
              <el-date-picker
                v-model="formData.baseYear"
                value-format="YYYY"
                type="year"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品产地：" prop="manufactureAddress">
              <el-select v-model="formData.manufactureAddress" placeholder="请选择">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in countryOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核算边界：" prop="accountBoundary">
              <el-select v-model="formData.accountBoundary">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in accountBoundaryOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="产品编码："
              prop="code"
              :rules="[
                {
                  validator: checkoutInput,
                  trigger: ['submit', 'change', 'blur']
                },
                {
                  required: true,
                  message: '产品编码不能为空',
                  trigger: ['submit', 'change']
                }
              ]"
            >
              <el-input v-model="formData.code" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报告编号：" prop="modelReportNo">
              <el-input v-model="formData.modelReportNo" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="认证机构：" prop="caName">
              <el-input v-model="formData.caName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报告文件：" prop="reportName">
              <GUpload
                class="accounting-form-upload"
                :action="action1"
                :postParams="{ filePath: 'sendLcaReport', needRename: 'false' }"
                ref="uploadRef"
                :show-file-list="true"
                :limit="100"
                v-model:fileList="fileList"
                accept=".pdf"
                @success="handleUploadSuccess"
                :on-change="onChange"
                @remove="handleRemove"
              >
                <template #default="{ loading: btnLoading }">
                  <el-button :loading="btnLoading"
                    ><CIcon type="c-xian-shangchuan" class="g-mr4"></CIcon>上传文件</el-button
                  >
                </template>
                <template #tip>
                  <div>
                    <span class="g-font-12n3-2">支持pdf格式文件，大小不超过20M。</span>
                  </div>
                </template>
              </GUpload>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="适用产品：" prop="applyProductCode">
              <template #default>
                <div class="product-list g-flex">
                  <el-button @click="showCode">
                    产品编码({{ formData.applyProductCode.length }}/20)
                  </el-button>
                </div>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="取舍规则：" prop="arRules" class="noflex-item">
              <el-input
                type="textarea"
                v-model="formData.arRules"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入"
              />
              <el-tooltip placement="bottom">
                <template #content
                  >1. 普通物料重量＜1%产品重量时，以及含稀贵或高纯成分的物料重量＜
                  0.1%产品重量时，<br />
                  可忽略该物料的上游生产数据；总共忽略的物料重量 不超过 5%； <br />
                  2. 低价值废物作为原料，如粉煤灰、矿渣、秸秆、生活垃圾等，可忽略其上游生产数据；
                  <br />
                  3. 大多数情况下，生产设备、厂房、生活设施等可以忽略； <br />
                  4. 在选定环境影响类型范围内的已知排放数据不应忽略。
                </template>
                <div class="rule-des">规则模板</div>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <ApplicationCodeDialog
      v-model:visible="codeVisible"
      :code="formData.code"
      :applyProductCode="formData.applyProductCode"
      @change="handleChangeData"
    />
  </div>
</template>
<script lang="ts" setup name="AccountingForm">
import { defineExpose, defineProps } from 'vue';
import { reactive, ref } from 'vue';
import {
  getModelSelectList,
  getDataRequestModelList,
  fileUploadRequestUrl,
  getModelBasicInfo
} from '@/apis/todo/flowBusiness';
import {
  ReplyTypeEnum,
  modelUnitAllOption,
  WeightUnitOption,
  countryOptions,
  accountBoundaryOptions
} from '@/constants/enum';
import { formRules } from './rules';
import { useWeightAndUnit } from '@/hooks/useWeightAndUnit';
import { GUpload } from '@/components/GUpload/index';
import ApplicationCodeDialog from './components/ApplicationCodeDialog/index.vue';
import { isRepeat } from '@/utils';
import { useMessage } from '@/hooks/useMessage';
import type {
  GetRequestInfoResult,
  GetModelBasicInfoResult
} from '@/apis/todo/model/flowBusinessModel';
import { useRouter } from 'vue-router';

const router = useRouter();
const action1 = fileUploadRequestUrl;
const formRef = ref();
const formData = reactive({
  replyType: 'MODEL' as keyof typeof ReplyTypeEnum, //回复类型  MODEL:模型   LCA:碳足迹报告
  modelNo: '',
  // LCA所选模型编号
  modelReportNo: '',
  weightUnit: 'kg',

  // 排放结果
  emissionResult: '',
  // 规格型号
  specification: '',
  // 核算数量
  num: '',
  // 单位重量
  weight: '',
  // 数据采集周期
  baseYear: '',
  // 产品产地
  manufactureAddress: '',
  // 核算边界
  accountBoundary: '',
  // 产品编码
  code: '',
  // 适用产品编码
  applyProductCode: [] as string[],
  // 取舍规则
  arRules: '',
  // 认证机构
  caName: '',
  // 报告名称
  reportName: '',
  // 报告地址
  reportUrl: '',
  // 核算单位
  unit: 'pcs'
});

const { createMessage } = useMessage();
const { isWeightUnitComputed } = useWeightAndUnit({
  props: formData
});

interface AccountingBaseInfoProps {
  requestNo: string;
  modelBaseInfo: GetRequestInfoResult;
}
const props = defineProps<AccountingBaseInfoProps>();

const modelList = ref();

async function getModelList() {
  try {
    let resData = [];
    if (props.modelBaseInfo.activeFlag) {
      resData = await getModelSelectList();
    } else {
      resData = await getDataRequestModelList(props.requestNo);
    }
    console.log('模型列表', resData, props.modelBaseInfo);
    modelList.value = resData || [];
  } catch (error) {
    console.log('error', error);
  }
}

const modelInfo = ref<GetModelBasicInfoResult>();
async function getData() {
  try {
    modelInfo.value = await getModelBasicInfo(props.requestNo, '1');
    console.log('modelInfo.value', modelInfo.value);
    modelInfo.value.replyType && (formData.replyType = modelInfo.value.replyType);
    if (formData.replyType === 'LCA') {
      formData.modelReportNo = modelInfo.value.modelNo;
      formData.emissionResult = modelInfo.value.accountResult;
      formData.specification = modelInfo.value.specification;
      formData.num = String(modelInfo.value.num);
      formData.weight = modelInfo.value.weight;
      formData.baseYear = modelInfo.value.baseYear;
      formData.manufactureAddress = modelInfo.value.manufactureAddress;
      formData.accountBoundary = modelInfo.value.accountBoundary;
      formData.code = modelInfo.value.code;
      formData.applyProductCode = modelInfo.value.applyProductCode;
      formData.arRules = modelInfo.value.arRules;
      formData.caName = modelInfo.value.caName;
      formData.reportName = modelInfo.value.reportName;
      formData.reportUrl = modelInfo.value.reportUrl;
      formData.unit = modelInfo.value.unit;
      if (modelInfo.value.reportUrl && modelInfo.value.reportName) {
        fileList.value = [{ name: modelInfo.value.reportName, url: modelInfo.value.reportUrl }];
      }
    }
  } catch (error) {
    console.log('error', error);
  }
}

function routerToCreateModel() {
  router.push('/myModel/addModel');
}

const codeVisible = ref(false);
// 以下内容是新添加的内容
// 点击产品编码的出发函数，需要判断是不是编辑还是新增
const showCode = () => {
  codeVisible.value = true;
};

const handleChangeData = (val: any) => {
  // 传递数组给父组件
  formData.applyProductCode = val;
  if (formData.code) {
    formRef.value.validateField('code');
  }
};
const checkoutInput = (rule: any, value: any, callback: any) => {
  // NOTE 为空的时候不做校验
  if (!value) callback();
  if (isRepeat(value, formData.applyProductCode) > 0) {
    return callback(new Error('编码已存在'));
  }
  callback();
};

const fileList = ref<any[]>([]);
const flag = ref(true);
const handleUploadSuccess = (file: any) => {
  console.log('handleUploadSuccess', file);
  if (file.response.msg == '成功') {
    formData.reportUrl = file.response.data.fileUrl;
    formData.reportName = file.name;
    createMessage.success('上传成功');
    flag.value = true;
    formRef.value.validateField('reportName');
  } else {
    createMessage.info('上传失败');
    formData.reportUrl = '';
    formData.reportName = '';
    flag.value = false;
  }
  // uploadRef.value?.clearFiles();
};

function handleRemove() {
  if (fileList.value.length === 0) {
    formData.reportUrl = '';
    formData.reportName = '';
    flag.value = false;
    formRef.value.validateField('reportName');
  }
}

const onChange = (file: any, fileList: any) => {
  console.log('onChange', fileList);
  if (fileList.length > 1) {
    if (flag.value == true) {
      fileList.splice(0, 1);
    }
  }
};

function submit() {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        if (formData.replyType === 'LCA') {
          formData.modelNo = formData.modelReportNo;
        }
        resolve(formData);
      } else {
        reject();
      }
    });
  });
}

getModelList();

getData();

defineExpose({
  submit
});
</script>
<style lang="scss" scoped>
.accounting-form {
  padding-top: 11px;
  width: 100%;
  .fill-type-radio {
    width: 100%;
    height: 30px;
  }
  .fill-type-tips {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #9196a3;
    line-height: 20px;
  }
  .form-container {
    padding: 12px 10px 6px;
    background: #f6f9fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }
  .select-model-input {
    width: 100%;
    height: 32px;
  }
  .select-model-tips {
    margin-top: 4px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #9196a3;
    line-height: 18px;
    .tips-href {
      color: #03ac82;
      cursor: pointer;
    }
  }
  .noflex-item {
    :deep(.el-form-item__content) {
      display: block;
    }
    .rule-des {
      color: $themeColor;
      width: 100px;
      line-height: 32px;
      cursor: pointer;
    }
  }
  :deep(.el-form .el-form-item__content) {
    .el-date-editor,
    .el-select {
      width: 100%;
    }
  }

  :deep(.accounting-form-upload.g-upload) {
    position: relative;
    width: 100%;
    .el-upload-list {
      position: absolute;
      right: 0;
      top: 0;
      margin: 0;
      min-width: calc(100% - 120px);
    }
  }
}
</style>
